const jwt = require('jsonwebtoken');
const util = require('util');
const verify = util.promisify(jwt.verify);

module.exports = async (ctx, next) => {
  // 获取jwt
  const token = ctx.header.authorization;
  if (!!token) {
    try {
      // 解密payload，获取用户名和ID
      let payload = await verify(token.split(' ')[1], 'shukan');
      ctx.user = {
        ...payload,
        code: 666,
        msg: 'token在有效期内'
      };
    } catch (err) {
      ctx.user = {
        code: 603,
        msg: 'token已过期'
      };
    }
  } else {
    ctx.user = {
      code: 111,
      msg: '缺少token'
    }
  }
  await next();
}
